﻿using CommonBase;
using CommonClass;
using DeviceMgtModule.Views;
using EncryptProject;
using EnvCommonUtility;
using InteractiveWhiteboardManagement.Base.Common;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Regions;
using SurveillanceLib;
using SurveillancePro.Base.Common;
using SurveillancePro.Base.Events;
using SurveillancePro.Base.Manager;
using SurveillancePro.Base.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace DeviceMgtModule.ViewModels
{
    /// <summary>
    /// 设备树
    /// </summary>
    public class ViewModel_DeviceTree : WorkspaceViewModel
    {
        #region Private Fields

        private DelegateCommand _cmdTreeNodeDoubleClick;
        private DelegateCommand<string> _cmdMenuItemClick;

        private TreeView _treeDevice; // 设备树
        private ITreeGroup _selectedTreeNode; // 所选结点

        private readonly IEventAggregator _eventAggregator;
        private readonly IRegionManager _regionManager;

        #endregion

        #region Constructor

        public ViewModel_DeviceTree(IEventAggregator eventAggregator,
            IRegionManager regionManager)
        {
            this._eventAggregator = eventAggregator;
            this._regionManager = regionManager;

            _loadDeviceTreeData(); // 设备树加载
            SurveillancePro.Base.Manager.EventManagers.RefreshTreeEvent += _loadDeviceTreeData; // 刷新主界面中的设备树
        }

        #endregion

        #region Base Class Overrides

        protected override void OnDispose()
        {
            _dispose();
        }

        #endregion

        #region Public Property

        /// <summary>
        /// 绑定树资源
        /// </summary>
        public ObservableCollection<ITreeGroup> TreeViewSource { get; set; }

        /// <summary>
        /// 双击叶子结点
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_TreeNodeDoubleClick
        {
            get
            {
                if (_cmdTreeNodeDoubleClick == null)
                {
                    _cmdTreeNodeDoubleClick = new DelegateCommand(_treeNodeDoubleClick, _canTreeNodeDoubleClick);
                }
                return _cmdTreeNodeDoubleClick;
            }
        }

        /// <summary>
        /// 右键菜单选择
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand<string> Cmd_MenuItemClick
        {
            get
            {
                if (_cmdMenuItemClick == null)
                {
                    _cmdMenuItemClick = new DelegateCommand<string>(_menuItemClick, _canMenuItemClick);
                }
                return _cmdMenuItemClick;
            }
        }

        #endregion

        #region Event

        /// <summary>
        /// 右键菜单的显示【Tree 右键菜单】
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TreeView_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            if (sender is TreeView)
            {
                _treeDevice = sender as TreeView; // 记录设备树
                if (_treeDevice.ContextMenu == null || 
                    _treeDevice.ContextMenu.Items.Count < 3 || 
                    _treeDevice.SelectedItem == null || 
                    !(_treeDevice.SelectedItem is ITreeGroup) ||
                    (_treeDevice.SelectedItem as ITreeGroup).Level >= 2 ||
                    (_treeDevice.SelectedItem as ITreeGroup).Arg == null ||
                    !((_treeDevice.SelectedItem as ITreeGroup).Arg is TagModel))
                {
                    e.Handled = true;
                    return;
                }

                _selectedTreeNode = _treeDevice.SelectedItem as ITreeGroup; // 记录所选结点，注：TreeView 没有 SelectedItem 公开属性，只有 get 访问器！
                if (_selectedTreeNode.Level == 0) // 根
                {
                    (_treeDevice.ContextMenu.Items[0] as MenuItem).IsEnabled = false; // 设备登录
                    (_treeDevice.ContextMenu.Items[1] as MenuItem).IsEnabled = false; // 注销设备
                    (_treeDevice.ContextMenu.Items[2] as MenuItem).IsEnabled = true; // 添加设备
                }
                else if (_selectedTreeNode.Level == 1) // 设备
                {
                    (_treeDevice.ContextMenu.Items[0] as MenuItem).IsEnabled = false;
                    (_treeDevice.ContextMenu.Items[1] as MenuItem).IsEnabled = true;
                    (_treeDevice.ContextMenu.Items[2] as MenuItem).IsEnabled = false;
                    if (!(_selectedTreeNode.Arg as TagModel).Driver_IsLogin)
                    {
                        (_treeDevice.ContextMenu.Items[0] as MenuItem).IsEnabled = true;
                        (_treeDevice.ContextMenu.Items[1] as MenuItem).IsEnabled = false;
                    }
                }
            }
        }

        #endregion

        #region Private Methods

        #region DelegateCommand

        private bool _canTreeNodeDoubleClick()
        {
            return true;
        }

        private bool _canMenuItemClick(string menu)
        {
            return true;
        }


        /// <summary>
        /// 双击叶子结点
        /// </summary>
        private void _treeNodeDoubleClick()
        {
            try
            {
                if (_treeDevice == null || _treeDevice.SelectedItem == null ||
                    !(_treeDevice.SelectedItem is ITreeGroup) || 
                    (_treeDevice.SelectedItem as ITreeGroup).Level != 2) // 只有叶子结点有效
                    return;

                this._eventAggregator.GetEvent<OpenModelEvent>().Publish(new OpenModelEventArg() { ModelName = "ViewModel_Shell", FunctionName = "SelectTreeNode", Arg = _treeDevice.SelectedItem, }); // 事件通知
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 右键菜单选择
        /// </summary>
        /// <param name="menu"></param>
        private void _menuItemClick(string menu)
        {
            switch (menu)
            {
                case "DeviceLogin": // 设备登陆
                    _deviceLogin();
                    break;
                case "DeviceLogout": // 注销设备
                    _deviceLogout();
                    break;
                case "DeviceManagement": // 设备管理
                    _deviceManagement();
                    break;



                default:
                    break;
            }
        }

        #endregion

        /// <summary>
        /// 加载设备树
        /// </summary>
        private void _loadDeviceTreeData()
        {
            try
            {
                if (TreeViewSource != null)
                    TreeViewSource.Clear();

                TreeViewSource = EnvUtilities.LoadDeviceTreeData(); // 绑定到树资源
                base.OnPropertyChanged("TreeViewSource");
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 设备登陆【Tree 右键菜单】
        /// </summary>
        private void _deviceLogin()
        {
            try
            {
                if (_selectedTreeNode != null &&
                    _selectedTreeNode.Arg != null && 
                    _selectedTreeNode.Arg is TagModel &&
                    (_selectedTreeNode.Arg as TagModel).Driver_Instance != null &&
                    !string.IsNullOrWhiteSpace((_selectedTreeNode.Arg as TagModel).Driver_IP) &&
                    !string.IsNullOrWhiteSpace((_selectedTreeNode.Arg as TagModel).Driver_Port) &&
                    !string.IsNullOrWhiteSpace((_selectedTreeNode.Arg as TagModel).Driver_User) &&
                    !string.IsNullOrWhiteSpace((_selectedTreeNode.Arg as TagModel).Driver_Password))
                {
                    NetDeviceInfoStruct deviceInfo; // 设备用户信息获得
                    int error = 0;
                    string pLoginID;

                    TagModel nodeTag = _selectedTreeNode.Arg as TagModel;
                    pLoginID = nodeTag.Driver_Instance.Login(nodeTag.Driver_IP, ushort.Parse(nodeTag.Driver_Port),
                        nodeTag.Driver_User,
                        EncryptAlgorithmHelper.Decrypt2(nodeTag.Driver_Password, Utilities.MachineCode),
                        out deviceInfo, out error); // 设备用户登录
                    if (!string.IsNullOrWhiteSpace(pLoginID) && deviceInfo.byChanNum > 0)
                    {
                        nodeTag.Driver_IsLogin = true; // 设备已登录
                        nodeTag.Driver_LoginID = pLoginID;
                        nodeTag.Driver_ChannelCount = deviceInfo.byChanNum; // 通道个数

                        string[] exceptChannels = null;
                        bool isExcept = false; // 表示是否为排除的通道号

                        if (!string.IsNullOrWhiteSpace(nodeTag.Driver_ExceptChannel))
                        {
                            exceptChannels = nodeTag.Driver_ExceptChannel.Split(','); // 得到所有排除的通道序列
                        }

                        for (int i = 0; i < deviceInfo.byChanNum; i++)
                        {
                            isExcept = false; // 未排除
                            if (exceptChannels != null && exceptChannels.Length > 0)
                            {
                                foreach (string channel in exceptChannels) // 排除通道号
                                {
                                    if (channel.Equals((i + 1).ToString()))
                                        isExcept = true;
                                }
                            }

                            if (isExcept)
                                continue;

                            TreeGroupModel leafChannel = new TreeGroupModel(string.Format("通道{0}", i + 1), null)
                            {
                                Parent = _selectedTreeNode,
                                Level = _selectedTreeNode.Level + 1,
                                TooltipText = string.Format("{0}通道{1}", _selectedTreeNode.TooltipText, i + 1),
                                Arg = new TagModel()
                                {
                                    Driver_IsLogin = nodeTag.Driver_IsLogin,
                                    Driver_Instance = nodeTag.Driver_Instance,
                                    Driver_IP = nodeTag.Driver_IP,
                                    Driver_LoginID = nodeTag.Driver_LoginID,
                                    Driver_Password = nodeTag.Driver_Password,
                                    Driver_Port = nodeTag.Driver_Port,
                                    Driver_Type = nodeTag.Driver_Type,
                                    Driver_User = nodeTag.Driver_User,
                                    Driver_ChannelCount = nodeTag.Driver_ChannelCount,
                                    Panel_SelectedChannel = i.ToString(),
                                },
                            };

                            _selectedTreeNode.Leaves.Add(leafChannel);
                        }

                        EventManagers.RefreshTreeWithLogin();
                    }
                    else
                    {
                        MessageBox.Show(nodeTag.Driver_Instance.GetLastOperationInfo(SurveillanceUtilities.ERR_INFO_FORMAT_STYLE), ConstantString.MSG_COMPANY); // 报最后一次操作的错误信息
                    }
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 注销设备【Tree 右键菜单】
        /// </summary>
        private void _deviceLogout()
        {
            try
            {
                if (_selectedTreeNode != null &&
                    _selectedTreeNode.Arg != null &&
                    _selectedTreeNode.Arg is TagModel &&
                    (_selectedTreeNode.Arg as TagModel).Driver_Instance != null &&
                    !string.IsNullOrWhiteSpace((_selectedTreeNode.Arg as TagModel).Driver_LoginID))
                {
                    TagModel nodeTag = _selectedTreeNode.Arg as TagModel;
                    if (nodeTag.Driver_Instance.Logout(nodeTag.Driver_LoginID))
                    {
                        // 1. 设备未登录
                        nodeTag.Driver_IsLogin = false;

                        // 2. 去 Tag 中的 loginID
                        nodeTag.Driver_LoginID = string.Empty;

                        // 3. 清空所有通道
                        _selectedTreeNode.Leaves.Clear();

                        // 4. 提示成功
                        MessageBox.Show("注销成功", ConstantString.MSG_COMPANY);

                        // 5. 刷新设备树【录像回放界面】
                        EventManagers.RefreshTreeWithLogin();
                    }
                    else
                        MessageBox.Show(nodeTag.Driver_Instance.GetLastOperationInfo(SurveillanceUtilities.ERR_INFO_FORMAT_STYLE), ConstantString.MSG_COMPANY); // 报最后一次操作的错误信息
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 设备管理【Tree 右键菜单】
        /// </summary>
        private void _deviceManagement()
        {
            try
            {
                if (this._regionManager != null)
                    this._regionManager.RequestNavigate(RegionNames.ContentRegion, ViewNames.DeviceMgtModule_DeviceManagement); // 显示设备管理界面
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        private void _dispose()
        {
            SurveillancePro.Base.Manager.EventManagers.RefreshTreeEvent -= _loadDeviceTreeData; // 反注册

            if (TreeViewSource != null)
                TreeViewSource.Clear();
        }

        #endregion
    }
}
